import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, DatePicker, Input, Select, message, InputNumber } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Customer from '../../components/Customer';
import { urlParse } from '@/utils/utils';
import styles from './style.less';

const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;

@connect(({ loading, oncechargecs }) => ({
  loading: loading.models.oncechargecs,
  product: oncechargecs.product, // 产品下拉
  empDataList: oncechargecs.empDataList, // 员工明细数据源
}))
@Form.create()
class AdvancedForm extends PureComponent {
  // 组件内所有数据的初始状态
  state = {
    CERT_TYPE: [],
    contList: [],
    onceFeeId: '',
  };

  componentDidMount() {
    const { form, dispatch, location } = this.props;
    const tempUrl = location.search;
    const { onceFeeId } = urlParse(tempUrl);
    this.setState({ onceFeeId });
    // 获取产品下拉
    dispatch({
      type: 'oncechargecs/getProductList',
      payload: {},
    });
    dispatch({
      type: 'oncechargecs/updateDetail',
      payload: { onceFeeId },
    }).then(res => {
      if (res.success) {
        res.data.busiYm = `${`${res.data.busiYm}`.substring(0, 4)}-${`${res.data.busiYm}`.substring(
          4
        )}`;
        if (res.data.feeYm) {
          res.data.feeYm = `${`${res.data.feeYm}`.substring(0, 4)}-${`${res.data.feeYm}`.substring(
            4
          )}`;
        }
        const getFieldsList = form.getFieldsValue();
        Object.keys(getFieldsList).forEach(key => {
          if (res.data[key]) {
            if (key === 'feeWay') {
              form.setFieldsValue({ [key]: res.data.feeWayName });
            } else if (key === 'pdId') {
              form.setFieldsValue({ [key]: res.data.pdName });
            } else if (key === 'custId') {
              form.setFieldsValue({ [key]: res.data.custName });
            } else if (key === 'custContId') {
              form.setFieldsValue({ [key]: res.data.custContName });
            } else if (key === 'busiYm') {
              form.setFieldsValue({ busiYm: moment(res.data.busiYm) });
            } else if (key === 'feeYm') {
              form.setFieldsValue({ feeYm: moment(res.data.feeYm) });
            } else {
              form.setFieldsValue({ [key]: res.data[key] });
            }
          }
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  }

  // 取消
  cancel = () => {
    router.goBack();
  };

  // 表单检测 并 提交
  submitAll = () => {
    const { form, dispatch } = this.props;
    const { onceFeeId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      let busiYm = '';
      if (!err) {
        Object.keys(values).forEach(key => {
          if (key === 'busiYm') {
            busiYm = values[key].format('YYYYMM');
          }
        });
        const submitData = {
          busiYm,
          onceFeeId,
          feeAmo: values.feeAmo,
          remark: values.remark,
        };
        if (String(values.feeAmo) === '0') {
          message.warning('收费金额不能为 0 ');
          return;
        }
        dispatch({
          type: 'oncechargecs/submitEmpData',
          payload: submitData,
        }).then(res => {
          if (res.success) {
            message.success('修改成功！');
            router.goBack();
          } else {
            message.warning(`${res.message || '修改失败！'}`);
          }
        });
      }
    });
  };

  // 客户名称
  getData = (value, id) => {
    const { form, dispatch } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
    dispatch({
      type: 'oncechargecs/getCustcontList',
      payload: { value },
    }).then(res => {
      if (res.success && res.data.length) {
        this.setState({ contList: res.data });
      } else {
        this.setState({ contList: [] });
      }
    });
  };

  // 渲染函数
  render() {
    const { product, form, submitting } = this.props;
    const { getFieldDecorator } = form;
    const { contList, CERT_TYPE } = this.state;
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Card title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>}>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="产品">
                  {getFieldDecorator('pdId', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <Select placeholder="请选择" onChange={this.getpdName} disabled>
                      {product.map(item => (
                        <Option key={item.pdCode} value={item.pdCode}>
                          {item.pdName}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<Customer getData={this.getData} disabled />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="商务合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: false, message: '请选择' }],
                  })(
                    <Select placeholder="请选择" disabled>
                      {contList.map(item => (
                        <Option key={item.contId} value={item.contId}>
                          {item.contName}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="姓名">
                  {getFieldDecorator('empName', {
                    rules: [{ required: true, message: '请选择' }],
                  })(<Input style={{ width: '100%' }} placeholder="请输入" disabled />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="证件号">
                  {getFieldDecorator('idNo', {
                    rules: [{ required: true, message: '请选择' }],
                  })(<Input style={{ width: '100%' }} placeholder="请输入" disabled />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="业务年月">
                  {getFieldDecorator('busiYm', {
                    rules: [{ required: true, message: '请选择' }],
                  })(<MonthPicker format="YYYY-MM" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="收费金额">
                  {getFieldDecorator('feeAmo', {
                    rules: [
                      { required: true, message: '保留小数点后两位', pattern: /^-?\d+\.?\d{0,2}$/ },
                    ],
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入"
                      min={0}
                      max={9999999.99}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={8}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<TextArea rows={4} maxLength={65} />)}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.submitAll} loading={submitting}>
              提交
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AdvancedForm;
